package org.hefan.org.service.impl;

import org.hefan.basic.service.impl.BaseServiceImpl;
import org.hefan.basic.util.MD5Utils;
import org.hefan.basic.util.StrUtils;
import org.hefan.org.domain.Employee;
import org.hefan.org.mapper.EmployeeMapper;
import org.hefan.org.service.IEmployeeService;
import org.hefan.user.domain.Logininfo;
import org.hefan.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * EmployeeServiceImpl实现类
 * 先继承再实现
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    @Transactional
    public void save(Employee employee) {
        //1.先保存t_employee对应的t_logininfo的信息 - 返回自增id
        //处理employee：添加salt，密码加密，设置type为员工0，然后保存
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);

        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);

        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);
    }

    @Override
    @Transactional
    public void remove(Long id) {
        // 传进来的employee表的id,通过id找到employee对象
        Employee employee = employeeMapper.loadById(id);
        // 找到employee的logininfo_id,也就是t_logininfo的id
        Long logininfo_id = employee.getLogininfo_id();
        // 先删除t_logininfo表里
        logininfoMapper.remove(logininfo_id);
        // 再删除t_employee表里
        employeeMapper.remove(id);
    }

    @Override
    @Transactional
    public void update(Employee employee) {
        // 生成新的盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 生成新的加密后的密码
        String newMd5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(newMd5Pwd);

        // 把employee对象转换成logininfo对象
        Logininfo logininfo = employee2Logininfo(employee);
        // 因为前台用户只会传employee的id,通过这个id在数据库查出这个employee对象
        Employee dbEmployee = employeeMapper.loadById(employee.getId());
        // 通过数据库这个employee对象,找到Logininfo_id,设置给这个logininfo对象的id
        // 因为是修改,所以必须设置logininfo对象的id
        logininfo.setId(dbEmployee.getLogininfo_id());

        logininfoMapper.update(logininfo);

        employeeMapper.update(employee);
    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0); // 员工,不是用户
        return logininfo;
    }
}
